<?php
require '../model/Db.php';
if(isset($_SERVER['HTTP_REFERER']) && $_GET['type'] ==1 || $_GET['type'] ==2 || $_GET['type'] ==3){
	$method = $_SERVER['REQUEST_METHOD'];
	header('Content-Type:application/json;charset=utf8');
	$Db = Db::getInstance();
    $user_data = $Db->islogin();
	if($method == 'GET'){
		$_GET = $Db->escape($_GET);
		if($_GET['type']==1){
			$where = "`user` = '{$_GET['user']}' or `email` = '{$_GET['email']}'";
		}else{
			$where = "`user` = '{$_GET['user']}' and `email` = '{$_GET['email']}'";
		}
		
	}else{
		$_POST = $Db->escape($_POST);
		$where = "(`user` = '{$_POST['user']}' and `pwd` = sha1(md5('{$_POST['pwd']}'))) or (`email` = '{$_POST['user']}' and `pwd` = sha1(md5('{$_POST['pwd']}')))";
	}
	$data = $Db->find([
		table => ['bbs_user'],
		where => $where
	]);
	$Db->close();
	if($method == 'GET'){
		if($_GET['type']==1){
			$ishaveuser = false;
			$ishaveemail = false;
			if(count($data) == 1){
				if($data[0]['user'] == $_GET['user']){
					$ishaveuser = true;
				}
				if($data[0]['email'] == $_GET['email']){
					$ishaveemail = true;
				}
			}elseif(count($data) == 2){
				$ishaveuser = true;
				$ishaveemail = true;
			}
			echo json_encode([ishaveuser => $ishaveuser,ishaveemail => $ishaveemail]);
		}else{
			if(count($data) == 1){
				$isOk = true;
			
			}else{
				$isOk = false;
				
			}
			echo json_encode([isok => $isOk]);
		}
		
	}else{
		$ishave = $data ? true : false;
		$islogin = $user_data ? true : false;
	    if($ishave && !$islogin){
	        $_SESSION['user'] = $data[0]['user'];
        	$_SESSION['pwd'] = sha1(md5($_POST['pwd']));
        	if($_POST['auto'] == 'true'){
        		setcookie(session_name(),session_id(),time()+AUTO_LOGIN_TIME,'/'
        	);
        	}
        	$reurl = $_SESSION['back'] ? $_SESSION['back'] : '/nsbbs/';
	    }
    	
    	echo json_encode([ishave => $ishave,islogin => $islogin,reurl => $reurl]);
    }
	
}else{
	http_response_code(404);
	echo '<h1 style="color:#337ab7">千呼万唤始出来,犹抱琵琶半遮面</h1>';
}

